package dao.Implementation;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;

import Donnees.Prix;
import Util.HibernateUtil;
import dao.Interfaces.IPrixDAO;

public class PrixDAO implements IPrixDAO {
	public PrixDAO() {
	}

	public List<Prix> selectAll() {
		List<Prix> listePrix = new ArrayList<Prix>();

		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tx = session.beginTransaction();

		listePrix.addAll(session.createQuery("from Prix").list());

		session.flush();
		tx.commit();
		session.close();

		return listePrix;
	}

	public long insert(Prix p) {
		Prix prixTemp = p;
		Long msgId;

		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tx = session.beginTransaction();

		msgId = (Long) session.save(prixTemp);

		session.flush();
		tx.commit();
		session.close();
		
		return msgId;
	}
	
	public int delete(Prix p) {
		Prix prixTemp = p;
		int retour;
		
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tx = session.beginTransaction();
		
		retour = session.createQuery("delete from Prix where valeur='" + prixTemp.getValeur() + "'").executeUpdate();

		session.flush();
		tx.commit();
		session.close();
		
		return retour;
	}
	
	public Prix getByValue(Double v) {
		Prix prixTemp = new Prix();

		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tx = session.beginTransaction();

		prixTemp = (Prix) session.createQuery("from Prix where valeur='" + v + "'").list().get(0);

		session.flush();
		tx.commit();
		session.close();

		return prixTemp;
	}
	
	public Prix getById(Long id) {
		Prix prixTemp = new Prix();

		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tx = session.beginTransaction();

		prixTemp = (Prix) session.createQuery("from Prix where id='" + id + "'").list().get(0);

		session.flush();
		tx.commit();
		session.close();

		return prixTemp;
	}
}
